﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web.ASPxUploadControl;
using Aij1.BLL;
using Aij1.Model;
using System.Drawing;
using Aij1.Utils;
using DevExpress.Xpo;
using DevExpress.Data.Filtering;

namespace Aij1.Cms
{
    public partial class Album : AdminPage
    {
        protected A_Article A;
        IList<A_Category> categorys;
        IList<ArticleStatusType> statusTypes;
        protected void Page_Load(object sender, EventArgs e)
        {
            PrepareData();
            categorys = CategoryData.GetCategorys(XpoSession);
            cbxCategory.DataSource = categorys;
            cbxCategory.DataBind();
            statusTypes = CategoryData.GetTypes<ArticleStatusType>();
            cbxStatus.DataSource = statusTypes;
            cbxStatus.DataBind();
            if (!IsPostBack && !IsCallback)
            {
                AssignAlbum();
                BindPhotoView();
            }
        }

        void PrepareData()
        {
            int albumId = CommOp.ToInt(Request["Id"]);

            if (albumId <= 0)
            {
                int catId = CommOp.ToInt(Request["CatId"]);
                A_Category cat = XpoSession.GetObjectByKey<A_Category>(catId);

                A = new A_Article(XpoSession)
                {
                    CategoryId = cat,
                    DisplayTime = DateTime.Now,
                    EditorId = CurrentUser,
                    Author = CurrentUser.TrueName,
                    Status = ArticleStatusType.审核通过,
                };
            }
            else
            {
                A = XpoSession.GetObjectByKey<A_Article>(albumId);
            }

            if (A == null)
            {
                Response.Write("相册未找到.");
                Response.End();
            }
        }

        void BindPhotoView()
        {
            RP.DataSource = A.Photos;
            RP.DataBind();
        }

        void AssignAlbum()
        {
            txtTitle.Text = A.Title;
            txtIntro.Text = A.Intro;
            txtAuthor.Text = A.Author;
            txtKeywords.Text = A.Keywords;
            txtSourceUrl.Text = A.SourceUrl;
            cbxStatus.Value = A.Status;
            dtDisplayTime.DateTime = A.DisplayTime;
            if (A.CategoryId != null)
            {
                cbxCategory.Text = A.CategoryId.Title;
            }
        }

        void GetAlbum()
        {
            PrepareData();

            A.Title = txtTitle.Text.Trim();
            A.Intro = txtIntro.Text.Trim();
            A.Author = txtAuthor.Text.Trim();
            A.EditorId = AuthData.GetCurrentUser(XpoSession);
            A.EditTime = DateTime.Now;
            A.DisplayTime = dtDisplayTime.DateTime;
            A.AType = ArticleType.相册;
            A.Keywords = txtKeywords.Text.Trim().Replace(",", ";");
            A.SourceUrl = txtSourceUrl.Text.Trim();
            if (cbxCategory.SelectedIndex >= 0)
            {
                A.CategoryId = categorys[cbxCategory.SelectedIndex];
            }
            if (cbxStatus.SelectedIndex >= 0)
            {
                A.Status = statusTypes[cbxStatus.SelectedIndex];
            }

            A.SamplePhotoId = A.Photos.FirstOrDefault(p => p.Oid == CommOp.ToInt(Request.Form["SamplePhotoId"]));
            if (A.SamplePhotoId == null && A.Photos.Count > 0)
            {
                A.SamplePhotoId = A.Photos[0];
            }
        }

        protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            A_Photo photo = AlbumData.CreatePhoto(XpoSession,
                  System.Drawing.Image.FromStream(e.UploadedFile.FileContent),
                  e.UploadedFile.FileName.Substring(0, e.UploadedFile.FileName.LastIndexOf('.')));

            AlbumData.RemovePhotoWhenExpired("PHOTO" + photo.Oid,
                photo.Oid + "|" + MapPath(photo.Url) + "|" + MapPath(photo.SnapShotUrl), 60);

            photo.Save();
            e.CallbackData = photo.Oid.ToString();
        }

        protected void ASPxCallback1_Callback(object source, DevExpress.Web.ASPxCallback.CallbackEventArgs e)
        {
            switch (e.Parameter)
            {
                case "pick":
                    GetAlbum();
                    e.Result = ArticleData.PickKeyword(A);
                    break;
                default:
                    AlbumData.GetPhotos(A, e.Parameter, false);
                    GetAlbum();
                    XpoSession.Save(A);
                    //XpoSession.Save(A.Photos);
                    e.Result = "保存成功！";
                    break;
            }
        }

        protected void ASPxCallback1_CustomJSProperties(object sender, DevExpress.Web.ASPxClasses.CustomJSPropertiesEventArgs e)
        {
            e.Properties["cpAlbumId"] = A.Oid;
            if (A.SamplePhotoId != null)
            {
                e.Properties["cpImgSample"] = ResolveClientUrl(A.SamplePhotoId.SnapShotUrl);
            }
        }

        protected string ImgSampleUrl
        {
            get
            {
                return A.SamplePhotoId == null ? "images/nopic.gif" : ResolveClientUrl(A.SamplePhotoId.SnapShotUrl);
            }
        }

        protected int ImgSampleOid
        {
            get
            {
                return A.SamplePhotoId == null ? 0 : A.SamplePhotoId.Oid;
            }
        }

        protected string GetUrl(object urlObj)
        {
            string url = urlObj as String;
            return String.IsNullOrEmpty(url) ? "images/nopic.gif" : ResolveUrl(url);
        }

        protected void callP_Callback(object sender, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
        {
            string p = e.Parameter;

            if (p.StartsWith("add:"))
            {
                p = p.Replace("add:", "");
                AlbumData.GetPhotos(A, p, true);
                A.Save();
            }

            else if (!String.IsNullOrEmpty(p))
            {
                AlbumData.GetPhotos(A, p, false);
                A.Save();
            }

            BindPhotoView();
        }
    }
}